package cn.lqz.bucttrain.service.impl;

import cn.lqz.bucttrain.enums.*;
import cn.lqz.bucttrain.exceptions.BaseException;
import cn.lqz.bucttrain.mapper.PassengerMapper;
import cn.lqz.bucttrain.mapper.UserMapper;
import cn.lqz.bucttrain.pojo.dto.UserPageQueryDTO;
import cn.lqz.bucttrain.pojo.entity.User;
import cn.lqz.bucttrain.pojo.vo.PageResultVO;
import cn.lqz.bucttrain.service.UserService;
import cn.lqz.bucttrain.utils.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Value("${service.default-password}")
    private String defaultPassword;
    @Resource
    private PassengerMapper passengerMapper;
    /**
     * 加载或查询用户
     * @param userPageQueryDTO
     * @return
     */
    @Override
    public PageResultVO loadUserList(UserPageQueryDTO userPageQueryDTO) {
        log.info("加载或查询用户列表：{}",userPageQueryDTO);
        PageHelper.startPage(userPageQueryDTO.getPageNo(),userPageQueryDTO.getPageSize());
        User userForQuery = new User();
        BeanUtils.copyProperties(userPageQueryDTO,userForQuery);
        Page<User> page = userMapper.findBatch(userForQuery);
        return new PageResultVO(userPageQueryDTO.getPageNo(),userPageQueryDTO.getPageSize(),page.getTotal(),page.getResult());
    }

    /**
     * 新增用户
     * @param user
     */
    @Override
    public void addOrUpdateUser(User user) {
        log.info("新增或修改用户：{}",user);
        // 新增
        if (user.getUserId()==null){
            // 电话号码已被使用
            User existPhoneNumber = userMapper.findByPhoneNumber(user.getPhoneNumber());
            if (existPhoneNumber!=null){
                throw new BaseException(ResponseCodeEnum.CODE_400.getCode(),"电话号码已被使用");
            }
            // 身份证号已被使用
            User existIdCard = userMapper.findByIdCard(user.getIdCard());
            if (existIdCard!=null){
                throw new BaseException(ResponseCodeEnum.CODE_400.getCode(),"身份证号已被使用");
            }
            // 设置默认密码
            user.setPassword(StringUtils.transferStringToMd5(defaultPassword));
            // 插入
            userMapper.insert(user);
        }else{ // 修改
            // 要修改成的电话号码已被使用
            User userByPhoneNumber = userMapper.findByPhoneNumber(user.getPhoneNumber());
            if (!userByPhoneNumber.getUserId().equals(user.getUserId())){
                throw new BaseException(ResponseCodeEnum.CODE_400.getCode(),"电话号码已被使用");
            }
            // 身份证号已被使用
            User userByIdCard = userMapper.findByIdCard(user.getIdCard());
            if (!userByIdCard.getUserId().equals(user.getUserId())){
                throw new BaseException(ResponseCodeEnum.CODE_400.getCode(),"身份证号已被使用");
            }
            // 修改
            userMapper.update(user);
        }
    }

    /**
     * 删除用户
     * @param userId
     */
    @Override
    @Transactional
    public void deleteUser(Long userId) {
        log.info("删除用户：userId={}",userId);
        // 删除该用户下的所有乘客
        passengerMapper.deleteByUserId(userId);
        // 用户删除后，其订单记录仍然保存
        userMapper.deleteByUserId(userId);
    }

    /**
     * 导出用户excel表
     */
    @Override
    public void exportUserExcel(List<User> userList, HttpServletResponse response) {
        log.info("用户：导出excel表");
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/用户报表.xlsx");
        try{
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            for(int i=1;i<=userList.size();i++){
                XSSFRow xssfRow = sheet.createRow(i);
                for(int j=0;j<6;j++){
                    xssfRow.createCell(j);
                }
            }
            for(int i=0;i<userList.size();i++){
                User user = userList.get(i);
                XSSFRow row = sheet.getRow(i + 1);
                row.getCell(0).setCellValue(user.getUserId());
                row.getCell(1).setCellValue(user.getPhoneNumber());
                row.getCell(2).setCellValue(user.getName());
                row.getCell(3).setCellValue(user.getIdCard());
                row.getCell(4).setCellValue(UserRoleTypeEnum.getByType(user.getRoleType()).getDescription());
                row.getCell(5).setCellValue(UserStatusEnum.getByStatus(user.getStatus()).getDescription());
            }
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            excel.close();
            inputStream.close();
        }catch (Exception e){
            log.error("订单导出excel表异常",e);
            throw new BaseException(ResponseCodeEnum.CODE_500);

        }
    }
}
